/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gla.centralhotel.dao;

import gla.centralhotel.dao.interfaces.IAgencyDAO;
import gla.centralhotel.exception.AgencySubscriptionException;
import gla.centralhotel.exception.IllegalAuthenticationException;
import gla.centralhotel.exception.NoUserFoundException;
import gla.centralhotel.model.Agency;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Rivo
 */
@Stateless
public class AgencyDAO implements IAgencyDAO {
    @PersistenceContext
    private EntityManager em;

    private Agency create(Agency agency) {
        em.persist(agency);
        return agency;
    }

    public Agency edit(Agency agency) {
        em.merge(agency);
        return agency;
    }

    public void remove(Agency agency) {
        em.remove(em.merge(agency));
    }

    public Agency find(Object id) {
        return em.find(gla.centralhotel.model.Agency.class, id);
    }

    public List<Agency> findAll() {
        return em.createQuery("select object(o) from Agency as o").getResultList();
    }
    
    public Agency findAgencyByLogin(String login) throws NoUserFoundException{
        Query q = em.createNamedQuery("Agency.findByLogin");
        q.setParameter("login", login);
        try{
            return (Agency) q.getSingleResult();
        }catch(NoResultException noREx){
            throw new NoUserFoundException("Aucun utilisateur n'a cet e-mail"+login);
        }catch(NonUniqueResultException e){
            throw new NoUserFoundException("ECHEC !!!");
        }
    }
    
    /**
     * MAJ Infos manager d'hotel
     * @param manager
     * @return
     */
    public Agency updateAgency(Agency agency)throws AgencySubscriptionException, IllegalAuthenticationException, NoUserFoundException{
        if(agency.getId() != null && agency.getLogin() != null && agency.getPassword() != null){
            try {
                Agency tmp = findAgencyByLogin(agency.getLogin());
                if (tmp.getId().compareTo(agency.getId()) == 0) {
                    return edit(agency);
                } else {
                    throw new IllegalAuthenticationException("Erreur de mise à jour :" + " id en base est différent de celui à mettre à jour");
                }
            } catch (NoUserFoundException ex) {
                Logger.getLogger(AgencyDAO.class.getName()).log(Level.SEVERE, null, ex);
                throw new NoUserFoundException("Aucun user trouvé !!");
            }
        }else{
            throw new AgencySubscriptionException("Mise à jour impossible les " +
                    "infos suivantes sont incorrectes : id et/ou email et/ou mote de passe");
        }
    }
    
    /**
     * Identifie l'utilisateur (agence) par "login - password"
     * @param email
     * @param pwd
     * @return
     * @throws javax.persistence.NoResultException
     * @throws javax.persistence.NonUniqueResultException
     */
    public Agency findAgencyByEmailPassword(String email, String pwd) throws IllegalAuthenticationException{
        String query = "select ag from Agency as ag where ag.login = :email and ag.password = :pwd";
        Query q = em.createQuery(query);
        q.setParameter("email", email);
        q.setParameter("pwd", pwd);
        try{
            return (Agency) q.getSingleResult();
        }catch(NoResultException noREx){
            throw new IllegalAuthenticationException("Aucun utilisateur trouvé!");
        }catch(NonUniqueResultException noUResEx){
            throw new IllegalAuthenticationException("ERREUR GRAVE, plusieurs utilisateurs pour un e-mail !!");
        }
    }
    
    /**
     * Ajoute une agence d'hotel et vérifie l'unicité du mail (mot de passe implicite)
     * @param manager
     * @return
     */
    public Agency saveAgency(Agency agency) throws AgencySubscriptionException, IllegalAuthenticationException {
        String email = "select ag from Agency as ag where ag.login = :login";
        if (agency.getId() == null && agency.getLogin() != null && agency.getPassword() != null) {
            Query mgrMail = em.createQuery(email);
            mgrMail.setParameter("login", agency.getLogin());
            List<Agency> agList = mgrMail.getResultList();
            if (agList.size() == 0) {
                agency = create(agency);
                return agency;
            } else {
                throw new AgencySubscriptionException("Email et mot de passe déjà utilisés");
            }
        } else {
            throw new IllegalAuthenticationException("E-mail ou mot de passe : null !!!!");
        }
    }

}
